package com.mimo.logic.session.grpc;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;

import com.google.protobuf.Any;
import com.google.protobuf.StringValue;
import com.mimo.common.logic.code.StatusCode;
import com.mimo.common.rpc.proto.BaseResponseProto.BaseResponse;
import com.mimo.common.rpc.proto.BaseResponseProto.BaseResponse.Builder;
import com.mimo.common.rpc.proto.BaseResponseProto.Singular;
import com.mimo.common.rpc.proto.LogicSessionProxyGrpc;
import com.mimo.common.rpc.proto.SessionProto.TouchReq;
import com.mimo.common.rpc.proto.UserProto.ZoneDTO;
import com.mimo.logic.config.heartbeat.annotation.ExcludeHeartbeat;
import com.mimo.logic.session.model.SessionInfo;
import com.mimo.logic.session.service.ISessionService;

import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;

@ExcludeHeartbeat
@GrpcService
public class LogicSessionGrpc extends LogicSessionProxyGrpc.LogicSessionProxyImplBase {

  @Autowired
  private ISessionService sessionService;

  @Override
  public void touch(TouchReq request, StreamObserver<BaseResponse> responseObserver) {
    sessionService.touch(request.getUid(), com.mimo.common.comet.dto.ZoneDTO.convert(request.getZone()));
    responseObserver.onNext(StatusCode.getSuccessInstance());
    responseObserver.onCompleted();
  }

  @Override
  public void getZoneByUserId(StringValue request, StreamObserver<BaseResponse> responseObserver) {
    Optional<ZoneDTO> opt = sessionService.findSessionByUser(request.getValue()).map(SessionInfo::getZone)
        .map(com.mimo.common.comet.dto.ZoneDTO::convert);

    Builder builder = BaseResponse.newBuilder();
    if (opt.isPresent()) {
      builder.setSingularValue(Singular.newBuilder().setItem(Any.pack(opt.get())).build());
    }

    responseObserver.onNext(builder.build());
    responseObserver.onCompleted();
  }

}
